<template>
  <div class="lawyer-add-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h2>{{ isEditMode ? '律师信息修改' : '律师信息添加' }}</h2>
      <el-button type="default" @click="handleGoBack">返回列表</el-button>
    </div>


    <!-- 主体表单卡片 -->
    <el-card class="form-card">
      <!-- 分页模式 -->
      <div v-if="displayMode === 'tabs'">
        <el-tabs v-model="activeTab" type="card" class="form-tabs" @tab-change="handleTabChange">
          <!-- 基本信息页 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-form
              :model="lawyerForm"
              ref="lawyerFormRef"
              :rules="lawyerFormRules"
              label-width="120px"
              :disabled="formLoading"
              class="lawyer-form"
            >
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="真实姓名" prop="realname">
                    <el-input v-model="lawyerForm.realname" placeholder="请输入真实姓名" maxlength="20" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="lawyerForm.sex" class="sex-radio-group">
                      <el-radio label="m" class="sex-radio">男</el-radio>
                      <el-radio label="f" class="sex-radio">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="民族" prop="nation">
                    <el-input v-model="lawyerForm.nation" placeholder="请输入民族" maxlength="10" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker
                      v-model="lawyerForm.birthday"
                      type="date"
                      placeholder="选择出生日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      :max="new Date()"
                      :disabled-date="disableFutureDate"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="政治面貌" prop="politicalStatus">
                    <el-input v-model="lawyerForm.politicalStatus" placeholder="请输入政治面貌（如：中共党员、群众）" maxlength="20" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="入党时间" prop="joinPartyDate">
                    <el-date-picker
                      v-model="lawyerForm.joinPartyDate"
                      type="date"
                      placeholder="选择入党时间（非党员可不填）"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      :max="new Date()"
                      :disabled-date="disableFutureDate"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="现居住地" prop="residence">
                <el-input v-model="lawyerForm.residence" placeholder="请输入现居住地（如：北京市朝阳区）" maxlength="50" show-word-limit />
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 教育信息页 -->
          <el-tab-pane label="教育信息" name="education">
            <el-form
              :model="lawyerForm"
              ref="lawyerFormRef"
              :rules="lawyerFormRules"
              label-width="120px"
              :disabled="formLoading"
              class="lawyer-form"
            >
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="毕业院校" prop="graduateSchool">
                    <el-input v-model="lawyerForm.graduateSchool" placeholder="请输入毕业院校" maxlength="50" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="专业" prop="major">
                    <el-input v-model="lawyerForm.major" placeholder="请输入专业（如：法学）" maxlength="30" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="学历" prop="education">
                <el-select v-model="lawyerForm.education" placeholder="请选择学历">
                  <el-option label="专科" value="专科" />
                  <el-option label="本科" value="本科" />
                  <el-option label="硕士" value="硕士" />
                  <el-option label="博士" value="博士" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 执业信息页 -->
          <el-tab-pane label="执业信息" name="practice">
            <el-form
              :model="lawyerForm"
              ref="lawyerFormRef"
              :rules="lawyerFormRules"
              label-width="120px"
              :disabled="formLoading"
              class="lawyer-form"
            >
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCard">
                    <el-input
                      v-model="lawyerForm.idCard"
                      placeholder="请输入18位身份证号"
                      maxlength="18"
                      show-word-limit
                      @blur="handleIdCardBlur"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phone">
                    <el-input
                      v-model="lawyerForm.phone"
                      placeholder="请输入11位手机号"
                      maxlength="11"
                      show-word-limit
                      @input="handlePhoneInput"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="业务邮箱" prop="email">
                    <el-input v-model="lawyerForm.email" placeholder="请输入业务邮箱（如：lawyer@example.com）" maxlength="50" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="执业证号" prop="licenseNo">
                    <el-input v-model="lawyerForm.licenseNo" placeholder="请输入律师执业证号" maxlength="20" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="取得职业资格日期" prop="qualificationDate">
                    <el-date-picker
                      v-model="lawyerForm.qualificationDate"
                      type="date"
                      placeholder="选择取得法律职业资格日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      :max="new Date()"
                      :disabled-date="disableFutureDate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="业务特长" prop="businessSpecialty">
                    <el-input v-model="lawyerForm.businessSpecialty" placeholder="请输入业务特长（如：刑事案件、民事案件、行政案件、经济案件、公益案件、破产案件、法援案件）" maxlength="50" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="是否合伙人" prop="isPartner">
                    <el-select v-model="lawyerForm.isPartner" placeholder="请选择是否合伙人">
                      <el-option label="是" :value="1" />
                      <el-option label="否" :value="0" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否担任代表" prop="representative">
                    <el-select v-model="lawyerForm.representative" placeholder="请选择是否担任人大代表/政协委员">
                      <el-option label="是" :value="1" />
                      <el-option label="否" :value="0" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="律师类型" prop="lawyerType">
                    <el-select v-model="lawyerForm.lawyerType" placeholder="请选择律师类型">
                      <el-option label="律师" value="律师" />
                      <el-option label="兼职律师" value="兼职律师" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="兼职工作单位"
                    prop="partTimeWork"
                    v-if="lawyerForm.lawyerType === '兼职律师'"
                  >
                    <el-input v-model="lawyerForm.partTimeWork" placeholder="请输入兼职工作单位（如：XX大学）" maxlength="50" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="工作状态" prop="workStatus">
                    <el-select v-model="lawyerForm.workStatus" placeholder="请选择工作状态">
                      <el-option label="在职" value="在职" />
                      <el-option label="离职" value="离职" />
                      <el-option label="休假" value="休假" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="聘用日期" prop="hireDate">
                    <el-date-picker
                      v-model="lawyerForm.hireDate"
                      type="date"
                      placeholder="选择律所聘用日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      :max="new Date()"
                      :disabled-date="disableFutureDate"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="受过的奖励" prop="award">
                    <el-input v-model="lawyerForm.award" placeholder="请输入受过的奖励（无则填“无”）" maxlength="100" show-word-limit />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="受过的处分" prop="punishment">
                    <el-input v-model="lawyerForm.punishment" placeholder="请输入受过的处分（无则填“无”）" maxlength="100" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="lawyerForm.remark"
                  placeholder="请输入备注信息（可选）"
                  type="textarea"
                  :rows="3"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 社保信息页 -->
          <el-tab-pane label="社保信息" name="social">
            <el-form
              :model="lawyerForm"
              ref="lawyerFormRef"
              :rules="lawyerFormRules"
              label-width="120px"
              :disabled="formLoading"
              class="lawyer-form"
            >
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="首次社保缴费日期" prop="firstSocialSecurityDate">
                    <el-date-picker
                      v-model="lawyerForm.firstSocialSecurityDate"
                      type="date"
                      placeholder="选择首次社保缴费日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      :max="new Date()"
                      :disabled-date="disableFutureDate"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="社保编号" prop="socialSecurityNo">
                    <el-input v-model="lawyerForm.socialSecurityNo" placeholder="请输入社保编号" maxlength="20" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>

          <!-- 其他信息页 -->
          <el-tab-pane label="其他信息" name="other">
            <el-form
              :model="lawyerForm"
              ref="lawyerFormRef"
              :rules="lawyerFormRules"
              label-width="120px"
              :disabled="formLoading"
              class="lawyer-form"
            >
              <el-form-item label="社会职务" prop="socialDutie">
                <el-input v-model="lawyerForm.socialDutie" placeholder="请输入社会职务（如：XX协会理事，无则填“无”）" maxlength="50" show-word-limit />
              </el-form-item>
              <el-form-item label="个人简历" prop="resume">
                <el-input v-model="lawyerForm.resume" placeholder="请输入个人简历（如：XX协会理事，无则填“无”）" maxlength="50" show-word-limit />
              </el-form-item>

              <el-form-item label="学术成果" prop="academicAchievements">
                <el-input
                  v-model="lawyerForm.academicAchievements"
                  placeholder="请输入学术成果（如：发表《XX论文》，无则填“无”）"
                  type="textarea"
                  :rows="2"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="法律顾问单位" prop="legalAdvisorUnits">
                <el-input v-model="lawyerForm.legalAdvisorUnits" placeholder="请输入法律顾问单位（无则填“无”）" maxlength="100" show-word-limit />
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 文件上传页 -->
          <el-tab-pane label="文件上传" name="files">
            <el-form
              :model="lawyerForm"
              ref="lawyerFormRef"
              :rules="lawyerFormRules"
              label-width="120px"
              :disabled="formLoading"
              class="lawyer-form"
            >
              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="个人照片" prop="photo">
                    <el-upload
                      class="upload-demo"
                      :file-list="photoFileList"
                      :on-change="(file) => handleCommonFileChange(file, photoFileList, 'photoFile', 'photo')"
                      :before-upload="beforePhotoUpload"
                      :limit="1"
                      accept="image/*"
                      :auto-upload="false"
                      :on-remove="handlePhotoRemove"
                    >
                      <el-button size="small" type="primary">点击上传照片</el-button>
                      <div class="upload-hint">支持JPG、PNG格式，大小不超过5MB</div>
                    </el-upload>
                    <div class="preview-container" v-if="lawyerForm.photo">
                      <el-image
                        :src="lawyerForm.photoPreviewUrl"
                        style="width: 150px; height: 150px"
                        fit="cover"
                        :preview-src-list="[lawyerForm.photo]"
                        preview-teleported
                      />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20" class="form-row">
                <el-col :span="12">
                  <el-form-item label="转所记录">
                    <el-upload
                      class="upload-component"
                      action=""
                      :auto-upload="false"
                      :on-change="(file) => handleCommonFileChange(file,transferFileList,'transferRecordsFile','transferRecords')"
                      :file-list="transferFileList"
                      accept=".pdf,.doc,.docx"
                      :limit="1"
                      :on-remove="handleTransferRecordsRemove"
                    >
                      <el-button size="small" type="primary">选择转所记录</el-button>
                      <template #tip>
                        <div class="el-upload__tip">支持PDF、DOC、DOCX格式，无则可不传</div>
                      </template>
                    </el-upload>
                    <el-button
                      size="small"
                      type="text"
                      @click="downloadLawyerFile(lawyerForm.transferRecords)"
                      v-if="lawyerForm.transferRecords"
                    >
                    下载转所记录
                    </el-button>
                    <div v-if="transferFileList.length > 0" class="selected-file">
                      {{ transferFileList[0].name }}
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="档案调转记录">
                    <el-upload
                      class="upload-component"
                      action=""
                      :auto-upload="false"
                      :on-change="(file) => handleCommonFileChange(file,fileTransferFileList,'fileTransferRecordsFile','fileTransferRecords')"
                      :file-list="fileTransferFileList"
                      accept=".pdf,.doc,.docx"
                      :limit="1"
                      :on-remove="handleFileTransferRecordsRemove"
                    >
                      <el-button size="small" type="primary">选择档案调转记录</el-button>
                      <template #tip>
                        <div class="el-upload__tip">支持PDF、DOC、DOCX格式，无则可不传</div>
                      </template>
                    </el-upload>
                    <el-button
                      size="small"
                      type="text"
                      @click="downloadLawyerFile(lawyerForm.fileTransferRecords)"
                      v-if="lawyerForm.fileTransferRecords"
                    >
                      查看档案调转记录
                    </el-button>
                    <div v-if="fileTransferFileList.length > 0" class="selected-file">
                      {{ fileTransferFileList[0].name }}
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 多证书上传 -->
              <el-form-item label="证书上传">
                <div v-for="(cert, index) in certificates" :key="cert.id || `new-${index}`" class="certificate-item">
                  <el-row :gutter="20" style="margin-top: 10px;">
                    <el-col :span="15">
                      <el-input
                        v-model="cert.certificateName"
                        placeholder="请输入证书名称"
                        maxlength="50"
                        show-word-limit
                      />
                    </el-col>
                    <el-col :span="5">
                      <el-upload
                        class="upload-demo"
                        action=""
                        :auto-upload="false"
                        :on-change="(file) => handleCommonFileChange(file, cert.fileList, '', '', index)"
                        :file-list="cert.fileList"
                        accept=".pdf,.jpg,.jpeg,.png"
                        :limit="1"
                        :before-upload="(file) => beforeCertUpload(file, index)"
                      >
                        <el-button size="small" type="default">选择文件</el-button>
                      </el-upload>
                      <div v-if="cert.fileList.length > 0" class="selected-file">
                        {{ cert.fileList[0].name }}
                      </div>
                      <el-button size="small"
                                 type="text"
                                 @click="downloadLawyerFile(cert.certificateUrl)"
                                 v-if="cert.fileList.length>0">
                        下载证书
                      </el-button>
                    </el-col>
                    <el-col :span="4">
                      <el-button
                        type="danger"
                        size="small"
                        @click="removeCertificate(index)"
                        icon="Delete"
                      />
                    </el-col>
                  </el-row>
                </div>

                <el-button
                  type="primary"
                  size="small"
                  @click="addCertificate"
                  icon="Plus"
                >
                  再填一份
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>


      <!-- 表单操作按钮 -->
      <div class="form-actions">
        <el-button @click="handleGoBack">取消</el-button>

        <!-- 分页模式下的导航按钮 -->
        <template v-if="displayMode === 'tabs'">
          <el-button
            v-if="activeTab !== 'basic'"
            type="default"
            @click="prevTab"
          >
            上一步
          </el-button>

          <el-button
            v-if="activeTab !== 'files'"
            type="primary"
            @click="nextTab"
          >
            下一步
          </el-button>

          <el-button
            v-if="activeTab === 'files'"
            type="primary"
            @click="submitForm"
            :loading="formLoading"
          >
            {{ isEditMode ? '确认修改' : '确认添加' }}
          </el-button>
        </template>

      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, watch, onUnmounted, onMounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import type { FormInstance } from 'element-plus'
import { ElMessage, FormRules, ElLoading } from 'element-plus'
import {addLawyer, editLawyer, getLawyerByUserId} from '@/api/lawyer'
// 在导入部分添加
import { useLoginStore } from '@/stores/login'  // 请根据实际路径调整


const loginStore = useLoginStore()
const route = useRoute()
const isEditMode = ref(false)





/// 移除onMounted中的重复逻辑，保留initFormData并在onMounted中调用
onMounted(() => {
  initFormData(); // 统一通过initFormData初始化
})


// 引入必要的工具函数和类型
import { getFileUrl } from "@/api/file";


interface Certificate {
  id?: number;  // 添加id字段
  certificateName: string;
  file?: File | null;
  fileList: any[];
  certificateUrl?: string;  // 添加URL字段
  isDeleted?: boolean;  // 标记是否需要删除
}

// 在响应式变量部分添加删除证书ID列表
const deleteCertificateIds = ref<number[]>([]);


// 获取Token
const getToken = () => {
  return sessionStorage.getItem("token") || "";
};

// 文件请求工具（用于获取带权限的文件）
const requestFile = async (fileName: string, responseType: 'blob' | 'text' = 'blob') => {
  if (!fileName || !getToken()) return null;

  try {
    const res = await fetch(
      getFileUrl(fileName),
      { headers: { 'Authorization': `Auth ${getToken()}` } }
    );

    if (!res.ok) throw new Error(`状态码: ${res.status}`);
    return responseType === 'blob' ? await res.blob() : await res.text();
  } catch (e) {
    ElMessage.error(`操作失败: ${(e as Error).message}`);
    return null;
  }
};

// 图片加载函数（转换fileName为可预览的URL）
const getImageWithToken = async (fileName: string) => {
  const blob = await requestFile(fileName);
  return blob ? URL.createObjectURL(blob) : '';
};



// 1. 添加文件删除处理函数（在文件上传相关区域）
// 在handlePhotoRemove函数下方添加
const handleTransferRecordsRemove = (file: any) => {
  transferFileList.value = [];
  lawyerForm.transferRecordsFile = null;
  // 编辑模式下标记需要删除原文件
  if (isEditMode.value) {
    // 后续在FormData中会用到这个标记
    lawyerForm.transferRecords = '';
  }
};

const handleFileTransferRecordsRemove = (file: any) => {
  fileTransferFileList.value = [];
  lawyerForm.fileTransferRecordsFile = null;
  // 编辑模式下标记需要删除原文件
  if (isEditMode.value) {
    lawyerForm.fileTransferRecords = '';
  }
};


const initFormData = async () => {
  deleteCertificateIds.value = [];
  // 只有编辑模式才需要查询数据
  try {
    const userId = loginStore.id;
    if (!userId) {
      ElMessage.warning('请先登录系统');
      router.push('/login'); // 或其他登录页
      return;
    }
    // 2. 用用户ID查询关联的律师信息
    const res = await getLawyerByUserId(userId);
    console.log("后端返回的证书数据",res.data.certificates)
    // console.log("律师信息："+JSON.stringify(res,null,2))
    // 3. 处理查询结果
    if (res.code === 200 && res.data && res.data.lawyerId) {

        isEditMode.value = true;
        Object.assign(lawyerForm, res.data);

        // 处理照片预览
        if (res.data.photo) {
          const previewUrl = await getImageWithToken(res.data.photo);
          lawyerForm.photoPreviewUrl = previewUrl  // 给 <el-image>
          lawyerForm.photo = res.data.photo // 保留原始文件名
          photoFileList.value = [{ name: res.data.photo, previewUrl }] // 给 <el-upload>
        }


      const setFileList = (field: keyof Lawyer, fileName: string) => {
        if (!fileName) return;
        const url = getFileUrl(fileName);
        lawyerForm[field] = fileName;
        const targetList =
          field === 'transferRecords'
            ? transferFileList
            : fileTransferFileList;
        targetList.value = [{ name: fileName, url }];
      };

      setFileList('transferRecords', res.data.transferRecords);
      setFileList('fileTransferRecords', res.data.fileTransferRecords);

        // 处理证书回显
        certificates.value = []
        if (res.data.certificates && res.data.certificates.length) {
          certificates.value = res.data.certificates?.map(cert => ({
            id: cert.id,
            certificateName: cert.certificateName ?? '',
            file: null,
            certificateUrl: cert.certificateUrl,
            fileList: cert.certificateUrl
              ? [{ name: cert.certificateUrl, url: getFileUrl(cert.certificateUrl), uid: cert.id }]
              : []
          })).filter(Boolean) || [];
          if (!certificates.value.length) {
            certificates.value.push({ certificateName: '', file: null, fileList: [] });
          }
        }

        // 数字类型转换
        lawyerForm.isPartner = Number(lawyerForm.isPartner) || 0;
        lawyerForm.representative = Number(lawyerForm.representative) || 0;

      } else {
        // 无数据→新增模式
      isEditMode.value = false
      ElMessage.info('未找到律师信息，请先填写')

    }
  } catch (error) {
    console.error('初始化表单数据失败:', error);
    // 网络错误等异常情况也允许进入新增模式
    isEditMode.value = false;
    // ElMessage.error('获取律师信息失败，请检查网络或稍后重试');
  }
}


// 律师表单类型
interface Lawyer {
  lawyerId: string;
  id: string;
  username: string;
  realname: string;
  sex: string;
  nation: string;
  birthday: string;
  graduateSchool: string;
  major: string;
  education: string;
  politicalStatus: string;
  joinPartyDate: string;
  idCard: string;
  phone: string;
  email?: string;
  residence: string;
  licenseNo: string;
  qualificationDate: string;
  businessSpecialty: string;
  isPartner: number;
  hireDate: string;
  lawyerType: string;
  partTimeWork?: string;
  representative: number;
  award: string;
  punishment: string;
  workStatus: string;
  remark: string;
  photo: string;
  resume: string;
  firstSocialSecurityDate: string;
  socialSecurityNo: string;
  socialDutie: string;
  academicAchievements: string;
  legalAdvisorUnits: string;
  fileTransferRecords: string;
  transferRecords: string;
  // 文件上传字段
  photoFile?: File | null;
  // resumeFile?: File | null;
  transferRecordsFile?: File | null;
  fileTransferRecordsFile?: File | null;
  photoPreviewUrl: string
}


//二、基础响应式变量和引用
// 路由实例
const router = useRouter()
// 显示模式：tabs-分页模式
const displayMode = ref('tabs')

// 分页模式相关
const activeTab = ref('basic')
const tabOrder = ['basic', 'education', 'practice', 'social', 'other', 'files']

//组件生命周期控制
const isAlive = ref(true)
onUnmounted(() => {
  isAlive.value = false
})

// 表单相关
const lawyerFormRef = ref<FormInstance>()
const formLoading = ref(false)


//三、核心数据对象
//律师表单数据
const lawyerForm = reactive<Lawyer>({
  lawyerId: '',
  id: loginStore.id || '',
  username: loginStore.username || '',
  realname: '',
  sex: 'm',
  nation: '',
  birthday: '',
  graduateSchool: '',
  major: '',
  education: '',
  politicalStatus: '',
  joinPartyDate: '',
  idCard: '',
  phone: '',
  email: '',
  residence: '',
  licenseNo: '',
  qualificationDate: '',
  businessSpecialty: '',
  isPartner: 0,
  hireDate: '',
  lawyerType: '',
  partTimeWork: '',
  representative: 0,
  award: '',
  punishment: '',
  workStatus: '',
  remark: '',
  photo: '',
  resume: '',
  firstSocialSecurityDate: '',
  socialSecurityNo: '',
  socialDutie: '',
  academicAchievements: '',
  legalAdvisorUnits: '',
  fileTransferRecords: '',
  transferRecords: '',
  photoPreviewUrl:''
})

// 文件上传列表
const photoFileList = ref<any[]>([])
// const resumeFileList = ref<any[]>([])
const transferFileList = ref<any[]>([])
const fileTransferFileList = ref<any[]>([])

// 证书列表
const certificates = ref<Certificate[]>([
  { certificateName: '', file: null, fileList: [] }
])



//四、工具函数
// 禁止选择未来日期
const disableFutureDate = (time: Date) => {
  return time.getTime() > Date.now();
};



// 根据标签页获取需要验证的字段
const getFieldsByTab = (tabName: string) => {
  const fieldMap: Record<string, string[]> = {
    basic: ['realname', 'sex', 'nation', 'birthday', 'politicalStatus', 'residence'],
    education: ['graduateSchool', 'major', 'education'],
    practice: ['idCard', 'phone', 'email', 'licenseNo', 'qualificationDate', 'lawyerType', 'workStatus', 'hireDate'],
    social: ['firstSocialSecurityDate', 'socialSecurityNo'],
    other: ['socialDutie', 'academicAchievements', 'legalAdvisorUnits'],
    files: [] // 文件上传页无需验证
  }
  return fieldMap[tabName] || []
}


const downloadLawyerFile = async (fileName: string) => {
  if (!fileName) {
    ElMessage.error('文件名不存在');
    return;
  }
  const blob = await requestFile(fileName);
  if (!blob) return;
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();

  setTimeout(() => {
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }, 100);
};




//五、事件处理和业务逻辑
// 监听律师类型变化，处理兼职字段显示
watch(() => lawyerForm.lawyerType, (newVal) => {
  if (newVal !== '兼职律师') {
    lawyerForm.partTimeWork = ''
  }
})

// 分页模式 - 处理标签页切换
const handleTabChange = async (tabName: string) => {
  // 获取当前标签页索引
  const currentIndex = tabOrder.indexOf(activeTab.value)
  const newIndex = tabOrder.indexOf(tabName)

  // 只在前进时验证当前页表单
  if (newIndex > currentIndex) {
    const isValid = await validateCurrentTab()
    if (!isValid) {
      // 验证失败，返回原标签页
      activeTab.value = tabOrder[currentIndex]
    }
  }
}

// 分页模式 - 验证当前页表单
const validateCurrentTab = async () => {
  // 根据当前标签页确定需要验证的字段
  const fieldsToValidate = getFieldsByTab(activeTab.value)

  try {
    await lawyerFormRef.value?.validateField(fieldsToValidate)
    return true
  } catch (error) {
    ElMessage.error('请完善当前页的必填信息')
    return false
  }
}

// 分页模式 - 上一步
const prevTab = () => {
  const currentIndex = tabOrder.indexOf(activeTab.value)
  if (currentIndex > 0) {
    activeTab.value = tabOrder[currentIndex - 1]
  }
}

// 分页模式 - 下一步
const nextTab = async () => {
  const isValid = await validateCurrentTab()
  if (isValid) {
    const currentIndex = tabOrder.indexOf(activeTab.value)
    if (currentIndex < tabOrder.length - 1) {
      activeTab.value = tabOrder[currentIndex + 1]
    }
  }
}


//七、文件上传相关
//证书上传前置校验
// 新增：证书上传前置校验（确保先填名称再传文件）
const beforeCertUpload = (file: File, index: number) => {
  // 获取当前证书项的名称
  const certName = certificates.value[index].certificateName?.trim();
  // 校验：若名称为空，拦截上传并提示
  if (!certName) {
    ElMessage.warning(`请先填写第${index + 1}个证书的名称`);
    return false; // 拦截文件上传
  }
  // 名称不为空时，允许上传（继续执行原逻辑）
  return true;
};

//通用文件上传处理
const handleCommonFileChange=(
  file: any,
  fileListRef:Ref<any[]>,
  targetField?: keyof Lawyer,
  previewField?: keyof Lawyer,
  index = -1
)=>{
  fileListRef.value = [file];
  const rawFile = file.raw;

  if (index > -1) {
    //多文件上传绑定到certificates数组
    certificates.value[index].fileList = [file]
    certificates.value[index].file = file.raw
  }else if (targetField) {
    lawyerForm[targetField] = rawFile;
  }

  if (previewField && rawFile?.type?.startsWith('image/')) {
    //先释放旧预览URL，避免内存泄漏
    if (lawyerForm[previewField] as string) {
      URL.revokeObjectURL(lawyerForm[previewField] as string);
    }
    lawyerForm[previewField] = URL.createObjectURL(rawFile);
  }
}


// 照片上传前置校验
const beforePhotoUpload = (file: File) => {
  const ok = file.type.startsWith('image/') && file.size / 1024 / 1024 < 5;
  if (!ok) ElMessage.error('图片格式或大小不符合要求');
  return ok;
};

// 添加证书
const addCertificate = () => {
  certificates.value.push({ certificateName: '', file: null, fileList: [] })
}

// 新增：删除个人照片的处理逻辑
const handlePhotoRemove = (file: any) => {
  // 1. 清空上传组件的文件列表
  photoFileList.value = [];
  // 2. 释放临时预览图URL，避免内存泄漏
  if (lawyerForm.photo) {
    URL.revokeObjectURL(lawyerForm.photo);
    lawyerForm.photo = ''; // 清空预览图URL，预览区自动隐藏（因 v-if="lawyerForm.photo"）
  }
  // 3. 清空表单中的真实图片文件字段，避免提交空文件
  lawyerForm.photoFile = null;
  // 编辑模式下需要标记为删除
  ElMessage.success('个人照片已删除');
};

// 移除证书
const removeCertificate = (index: number) => {
  const cert = certificates.value[index];
  if (cert.id) {
    deleteCertificateIds.value.push(cert.id);
  }
  certificates.value.splice(index, 1);

  // 确保至少保留一个证书项
  if (certificates.value.length === 0) {
    certificates.value.push({ certificateName: '', file: null, fileList: [] });
  }
}


//七、表单校验和提交
// 身份证号验证
const handleIdCardBlur = () => {
  const idCard = lawyerForm.idCard
  if (!idCard) return

  // 简单的身份证号格式验证（18位数字或最后一位为X）
  const reg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  if (!reg.test(idCard)) {
    ElMessage.warning('请输入有效的18位身份证号')
  }
}

// 手机号输入处理
const handlePhoneInput = (value: string) => {
  // 只保留数字
  lawyerForm.phone = value.replace(/[^\d]/g, '')
}

// 提交表单
const submitForm = async () => {
  try {
    // 全表单验证
    await lawyerFormRef.value?.validate()
    // 新增：证书“名称-文件”一一对应校验
    const invalidCerts = certificates.value.filter((cert, index) => {
      const hasName = !!cert.certificateName?.trim();
      const hasFile = !!cert.file;
      // 筛选出“有名称无文件”或“有文件无名称”的无效项
      return (hasName && !hasFile) || (!hasName && hasFile);
    });

    // 若存在无效项，提示并终止提交
    if (invalidCerts.length > 0) {
      ElMessage.error("所有证书项需同时填写名称和选择文件（空项请删除）");
      return; // 终止提交流程
    }

    formLoading.value = true

    // 构建FormData对象
    const formData = new FormData()

    // 必传：当前用户ID
    formData.append('id', loginStore.id || '');
    // 编辑模式必传律师ID
    if (isEditMode.value) {
      formData.append('lawyerId', lawyerForm.lawyerId);
    }


    // 添加基本信息字段
    Object.keys(lawyerForm).forEach(key => {
      // 排除文件相关字段
      if (!['photoFile', 'transferRecordsFile', 'fileTransferRecordsFile'].includes(key) && lawyerForm[key]) {
        formData.append(key, lawyerForm[key])
      }
    })

    // 优先使用 lawyerForm.photoFile（与表单字段同步，逻辑更清晰）
    if (lawyerForm.photoFile) {
      formData.append('photo', lawyerForm.photoFile);
    }

    if (lawyerForm.transferRecordsFile) {
      formData.append('transferRecords', lawyerForm.transferRecordsFile)
    }
    if (lawyerForm.fileTransferRecordsFile) {
      formData.append('fileTransferRecords', lawyerForm.fileTransferRecordsFile)
    }


    if (isEditMode.value && deleteCertificateIds.value.length > 0) {
      deleteCertificateIds.value.forEach(id => {
        formData.append('deleteCertificateIds', id.toString());
      });
    }

    // 添加证书名称列表
    certificates.value.forEach((cert, index) => {
      // 跳过标记为删除的证书
      if (cert.isDeleted) return;
      if (cert.file && cert.certificateName) {
        formData.append('certificateFiles', cert.file)
        formData.append('certificateNames', cert.certificateName)
      }
    })

    // 创建加载实例
    const loadingInstance = ElLoading.service({
      lock: true,
      text: isEditMode.value ? '正在保存修改...' : '正在添加律师信息...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 保存基本信息
    // const lawyerRes = await addLawyer(formData)

    const lawyerRes = isEditMode.value ? await editLawyer(formData) : await addLawyer(formData)
    if (lawyerRes.code === 200) {  // 改为判断请求成功
      ElMessage.success(isEditMode.value ? '修改成功' : '添加成功');
      // 修复判断条件，添加成功后切换到编辑模式
      if (!isEditMode.value) {
        isEditMode.value = true;
        await initFormData(); // 重新加载数据
      }
    } else {
      ElMessage.error(lawyerRes.msg || (isEditMode.value ? '修改律师信息失败' : '添加律师信息失败'))
    }

    loadingInstance.close();
  }catch (error) {
    if (isAlive.value) { // 检查组件存活状态
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请检查表单或网络')
    }
  } finally {
    if (isAlive.value) { // 检查组件存活状态
      formLoading.value = false
      // 确保关闭加载实例
      try {
        ElLoading.service().close()
      } catch (e) {
        // 忽略已关闭的错误
      }
    }
  }
}



// 返回列表页
const handleGoBack = () => {
  router.push('/dashboard') // 假设列表页路由为/lawyer-list
}


//八、表单验证规则
// 表单验证规则
const lawyerFormRules = reactive<FormRules>({
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  nation: [
    { required: true, message: '请输入民族', trigger: 'blur' }
  ],
  graduateSchool: [
    { required: true, message: '请输入毕业院校', trigger: 'blur' }
  ],
  major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
  education: [
    { required: true, message: '请选择学历', trigger: 'change' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入有效的18位身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入业务邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确', trigger: 'blur' }
  ],
  licenseNo: [
    { required: true, message: '请输入执业证号', trigger: 'blur' }
  ],
  lawyerType: [
    { required: true, message: '请选择律师类型', trigger: 'change' }
  ],
  partTimeWork: [
    {
      required: () => lawyerForm.lawyerType === '兼职律师',
      message: '请输入兼职工作单位',
      trigger: 'blur'
    }
  ],
  workStatus: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ],
  hireDate: [
    { required: true, message: '请选择聘用日期', trigger: 'change' }
  ]
})

</script>

<style scoped>
.lawyer-add-container {
  width: 100%;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.display-mode-switch {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
}

.form-card {
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden;
}

.lawyer-form {
  padding: 20px 20px 0;
}

.form-tabs {
  margin-bottom: 20px;
}

.form-collapse {
  border: none;
}

.el-collapse-item__content {
  padding-bottom: 15px !important;
}

.section-divider {
  margin: 20px 0;
}

.form-row {
  margin-bottom: 15px;
}

.sex-radio-group {
  display: flex;
  gap: 20px;
  margin-top: 5px;
}

.upload-component {
  margin-bottom: 10px;
}

.certificate-item {
  padding: 1px;
  border: 1px dashed #e6e6e6;
  border-radius: 4px;
  margin-top: 1px;
}

.selected-file {
  color: #666;
  font-size: 0.9rem;
  margin-top: 5px;
  word-break: break-all;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px;
  border-top: 1px solid #e6e6e6;
  margin-top: 20px;
}
</style>
